package com.spc.demo.factory;

import com.spc.demo.base.Provider;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author pingchao.su
 * @date 2022/6/18 17:48
 */
@Service
public class ProviderFactory {
    public static final Map<String, Provider> PROVIDER_REGISTRY = new ConcurrentHashMap<>(1);

    public ProviderFactory(List<Provider> providers) {
        providers.forEach(provider -> PROVIDER_REGISTRY.put(provider.type(), provider));
    }

    /*
     * 简单工厂，传入type，返回Provider
     * */
    public Provider get(String type) throws Exception {
        if (!PROVIDER_REGISTRY.containsKey(type)) {
            throw new Exception("type of [{}] not supported yet");
        }
        return PROVIDER_REGISTRY.get(type);
    }
}
